<template>
    <div>
        <p>vue.set的使用</p>
        <el-button @click="addSex">给friends对象添加sex属性</el-button>
        <el-button @click="delSex">给friends对象清空sex属性</el-button>
        <el-button @click="addDataPro">给data对象添加数据</el-button>
        <ul>
            <li>{{student.name}} - {{student.age}} - {{student.sex}}</li>
           
            <li v-for="(item,index) in student.friends" :key="index">
                <span>姓名：{{item.name}}-</span> 
                <span v-if="item.sex">性别：{{item.sex}}-</span>
                <span>年龄：{{item.age}}</span><br/>
            </li>
        </ul>
        <hr/>
        <div>
            <p>给数组添加数据绑定</p>
            <el-button @click="modifyFirst">通过下标修改第一个数据</el-button>

            性格：
            
            <ul>
                <li v-for="(item,index) in student.hobits" :key="index">
                    {{item}}
                </li>
            </ul>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            student:{
                name: '马冬梅',
                age: 20,
                sex: '女',
                friends: [
                    {
                        name: '马晓梅',
                        age: 21,
                        sex: '女',
                    },
                    {
                        name: '周小红',
                        age: 19,
                        sex: '男',
                    }
                ],
                hobits: [
                    '抽烟',
                    '喝酒',
                    '打牌'
                ]
            }
        }
    },
   mounted(){
       console.log('数据：',this.student);
   },
    methods: {
        addSex() {
           let frinedLen =  this.student.friends.length
            for (let i = 0; i < frinedLen; i++) {
                this.$set(this.student.friends[i],'sex','女')
                
            }
        },
        delSex() {
            let frinedLen =  this.student.friends.length
            for (let i = 0; i < frinedLen; i++) {
                this.$set(this.student.friends[i],'sex','')
                
            }
        },

        // 错误的写法
        addDataPro() {
            this.$set(this,'leader','小马')
        },

        modifyFirst() {
            this.$set(this.student.hobits,0,'打架')
        }

    }
    
}
</script>